<template>
  <div class="detail-container">
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>工艺品详情</el-breadcrumb-item>
    </el-breadcrumb>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else-if="goods" class="goods-detail">
      <div class="header">
        <h1>{{ goods.name }}</h1>
        <div class="tags">
          <el-tag v-for="tag in goods.tags" :key="tag.id" type="info" effect="plain" class="tag">{{ tag.name }}</el-tag>
          <el-tag type="primary">{{ goods.category?.name }}</el-tag>
        </div>
      </div>
      
      <div class="main-content">
        <div class="left-content">
          <el-image :src="'/api' + goods.cover" fit="cover" class="cover-image" />
          
          <div class="info-section">
            <h2>基本信息</h2>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="朝代">{{ goods.history?.period || '无' }}</el-descriptions-item>
              <el-descriptions-item label="地区">{{ goods.history?.region || '无' }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div class="history-section">
            <h2>历史文化背景</h2>
            <div v-if="goods.history" class="history-content">
              <p v-if="goods.history.cultural_background"><strong>文化背景：</strong>{{ goods.history.cultural_background }}</p>
              <p v-if="goods.history.craft_process"><strong>工艺流程：</strong>{{ goods.history.craft_process }}</p>
              <p v-if="goods.history.cultural_value"><strong>文化价值：</strong>{{ goods.history.cultural_value }}</p>
            </div>
            <el-empty v-else description="暂无历史信息" />
          </div>
        </div>
        
        <div class="right-content">
          <div class="content-section">
            <h2>介绍</h2>
            <div v-html="goods.content"></div>
          </div>
          
          <div class="historical-figures" v-if="goods.historicalFigures?.length || goods.knowledgeGraph?.historicalFigures?.length">
            <h2>相关历史人物</h2>
            <el-card v-for="figure in goods.historicalFigures || goods.knowledgeGraph?.historicalFigures" :key="figure.name || figure.id" class="figure-card">
              <template #header>
                <div class="card-header">
                  <span>{{ figure.name }}</span>
                </div>
              </template>
              <div class="card-content">{{ figure.description || '暂无描述' }}</div>
            </el-card>
          </div>
          
          <div class="historical-events" v-if="goods.historicalEvents?.length || goods.knowledgeGraph?.historicalEvents?.length">
            <h2>相关历史事件</h2>
            <el-timeline>
              <el-timeline-item
                v-for="event in goods.historicalEvents || goods.knowledgeGraph?.historicalEvents"
                :key="event.name || event.id"
                :timestamp="event.date || '未知时间'"
                placement="top"
              >
                <el-card>
                  <h4>{{ event.name }}</h4>
                  <p>{{ event.description || '暂无描述' }}</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </div>
      
      <div class="knowledge-graph-section">
        <h2>知识图谱</h2>
        <knowledge-graph-new :goods-id="goodsId" :key="`kg-${goodsId}`" />
      </div>
      
      <div class="related-goods" v-if="goods.knowledgeGraph?.relatedGoods?.length">
        <h2>相关工艺品</h2>
        <el-row :gutter="16">
          <el-col :span="6" v-for="related in goods.knowledgeGraph.relatedGoods" :key="related.id">
            <el-card shadow="hover" @click="navigateToDetail(related.id)" class="related-card">
              <img :src="'/api' + related.cover" class="related-image" />
              <div class="related-name">{{ related.name }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <div class="recommendation-section">
        <h2>猜你喜欢</h2>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="个性化推荐" name="personalized">
            <div v-if="personalizedRecommendations.length" class="recommendations-grid">
              <el-card 
                v-for="item in personalizedRecommendations" 
                :key="item.id" 
                shadow="hover" 
                @click="navigateToDetail(item.id)"
                class="recommendation-card"
              >
                <img :src="'/api' + item.cover" class="recommendation-image" />
                <div class="recommendation-name">{{ item.name }}</div>
                <div class="recommendation-reason" v-if="item.reasons && item.reasons.length">
                  <el-tooltip 
                    v-for="(reason, idx) in item.reasons" 
                    :key="idx"
                    :content="typeof reason === 'string' ? reason : (reason.type + ': ' + reason.name)"
                    placement="top"
                  >
                    <el-tag size="small" effect="plain">{{ typeof reason === 'string' ? reason : reason.name }}</el-tag>
                  </el-tooltip>
                </div>
              </el-card>
            </div>
            <el-empty v-else description="暂无推荐" />
          </el-tab-pane>
          <el-tab-pane label="历史文化相关" name="historical">
            <div v-if="historicalRecommendations.length" class="recommendations-grid">
              <el-card 
                v-for="item in historicalRecommendations" 
                :key="item.id" 
                shadow="hover" 
                @click="navigateToDetail(item.id)"
                class="recommendation-card"
              >
                <img :src="'/api' + item.cover" class="recommendation-image" />
                <div class="recommendation-name">{{ item.name }}</div>
                <div class="recommendation-reason" v-if="item.reasons && item.reasons.length">
                  <el-tooltip 
                    v-for="(reason, idx) in item.reasons" 
                    :key="idx"
                    :content="typeof reason === 'string' ? reason : (reason.type + ': ' + reason.name)"
                    placement="top"
                  >
                    <el-tag size="small" effect="plain">{{ typeof reason === 'string' ? reason : reason.name }}</el-tag>
                  </el-tooltip>
                </div>
              </el-card>
            </div>
            <el-empty v-else description="暂无推荐" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    
    <el-empty v-else description="未找到商品信息" />
    
    <div class="action-buttons">
      <el-button type="primary" @click="collectGoods" :disabled="!goods">
        <el-icon><Star /></el-icon> 收藏
      </el-button>
      <el-button type="success" @click="shareGoods" :disabled="!goods">
        <el-icon><Share /></el-icon> 分享
      </el-button>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, computed, onActivated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowRight, Star, Share } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import KnowledgeGraphNew from '@/components/KnowledgeGraphNew.vue';
import userActionMixin from '@/mixins/userActionMixin';
import {detailByID} from '@/api/goods.js'
const { recordView, recordCollect, recordShare } = userActionMixin();
import {historicalApi, personalizedApi} from '@/api/recommend.js'
const route = useRoute();
const router = useRouter();


const loading = ref(true);
const goods = ref(null);
const goodsId = computed(() => route.params.id);
const activeTab = ref('personalized');
const personalizedRecommendations = ref([]);
const historicalRecommendations = ref([]);

onMounted(async () => {
  if (!goodsId.value) {
    ElMessage.error('商品ID不能为空');
    router.push('/');
    return;
  }
  
  await fetchGoodsDetail();
  fetchRecommendations();
});

onActivated(async () => {
  if (!goodsId.value) {
    ElMessage.error('商品ID不能为空');
    router.push('/');
    return;
  }
  
  if (!goods.value || goods.value.id != goodsId.value) {
    await fetchGoodsDetail();
    fetchRecommendations();
  }
});

const fetchGoodsDetail = async () => {
  loading.value = true;
  console.log(`开始获取商品ID: ${goodsId.value} 的详情数据`);
  try {
    const response = await detailByID(goodsId.value)
    console.log('商品详情API响应:', response)
    if (response.code === 200) {
      goods.value = response.data;
      console.log(`成功加载商品详情数据:`, goods.value.name);
      // 记录浏览行为
      await recordView(goodsId.value);
    } else {
      console.error(`获取商品详情失败: ${response.message}`);
      ElMessage.error(response.message || '获取商品详情失败');
    }
  } catch (error) {
    console.error('获取商品详情失败:', error);
    ElMessage.error('获取商品详情失败');
  } finally {
    loading.value = false;
  }
};

const fetchRecommendations = async () => {
  try {
    // 获取个性化推荐
    const personalizedRes = await personalizedApi();
    if (personalizedRes.code === 200) {
      personalizedRecommendations.value = personalizedRes.data || [];
    } else {
      console.error('获取个性化推荐返回错误:', personalizedRes.message);
      personalizedRecommendations.value = [];
    }
    
    // 获取历史文化推荐
    const historicalRes = await historicalApi();
    if (historicalRes.code === 200) {
      historicalRecommendations.value = historicalRes.data || [];
    } else {
      console.error('获取历史文化推荐返回错误:', historicalRes.message);
      historicalRecommendations.value = [];
    }
  } catch (error) {
    console.error('获取推荐失败:', error);
    personalizedRecommendations.value = [];
    historicalRecommendations.value = [];
  }
};

const navigateToDetail = (id) => {
  if (id === goodsId.value) return;
  router.push(`/detail/${id}`);
};

const collectGoods = async () => {
  try {
    await recordCollect(goodsId.value);
    ElMessage.success('收藏成功');
  } catch (error) {
    console.error('收藏失败:', error);
    ElMessage.error('收藏失败');
  }
};

const shareGoods = async () => {
  try {
    // 假设 recordShare 是一个异步函数
    await this.recordShare(this.goodsId.value);
    const url = window.location.href;
    const title = this.goods.value.name;
    const text = `我发现了一个很有趣的手工艺品：${this.goods.value.name}`;


  } catch (error) {
    console.error('分享失败:', error);
  }
};
</script>

<style scoped lang="scss">
.detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading-container {
  margin-top: 40px;
}

.goods-detail {
  margin-top: 20px;
}

.header {
  margin-bottom: 20px;
  
  h1 {
    margin-bottom: 10px;
  }
  
  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
}

.main-content {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.left-content {
  flex: 0 0 40%;
}

.right-content {
  flex: 1;
}

.cover-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
  margin-bottom: 20px;
}

.info-section, .history-section, .content-section, .historical-figures, .historical-events {
  margin-bottom: 30px;

  h2 {
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
  }
}

.history-content {
  p {
    margin-bottom: 10px;
  }
}

.figure-card, .event-card {
  margin-bottom: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.knowledge-graph-section {
  margin-bottom: 30px;
  
  h2 {
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
  }
}

.related-goods, .recommendation-section {
  margin-bottom: 30px;
  
  h2 {
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
  }
}

.related-card, .recommendation-card {
  cursor: pointer;
  transition: transform 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }
}

.related-image, .recommendation-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.related-name, .recommendation-name {
  margin-top: 10px;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.recommendation-reason {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}
</style> 